package com.tsd.core.aspect;

import com.tsd.core.annotation.RepeatSubmit;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.utils.LockUtil;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HttpResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.concurrent.locks.Lock;

/**
 * @ClassName: RepeatSubmitAspect
 * @Description: TODO
 * @Author: Hillpool
 * @Date: 2023/7/28 14:15
 * @Version: 1.0
 */
@Aspect
@Component
public class RepeatSubmitAspect {

    public static final Logger LOGGER = LoggerFactory.getLogger(RepeatSubmitAspect.class);

    /**
     * 定义 @Pointcut注解表达式, 通过特定的规则来筛选连接点, 就是Pointcut，选中那几个你想要的方法
     * 在程序中主要体现为书写切入点表达式（通过通配、正则表达式）过滤出特定的一组 JointPoint连接点
     * 方式一：@annotation：当执行的方法上拥有指定的注解时生效（本博客采用这）
     * 方式二：execution：一般用于指定方法的执行
     */
    @Pointcut("@annotation(repeatSubmit)")
    public void pointCutNoRepeatSubmit(RepeatSubmit repeatSubmit) {
    }

    /**
     * 环绕通知, 围绕着方法执行
     *
     * @param joinPoint
     * @param repeatSubmit
     * @return
     * @throws Throwable
     * @Around 可以用来在调用一个具体方法前和调用后来完成一些具体的任务。
     * <p>
     * 方式一：单用 @Around("execution(* net.wnn.controller.*.*(..))")可以
     * 方式二：用@Pointcut和@Around联合注解也可以（本博客采用这个）
     * <p>
     * <p>
     * 两种方式
     * 方式一：加锁 固定时间内不能重复提交
     * <p>
     * 方式二：先请求获取token，这边再删除token,删除成功则是第一次提交
     */
    @Around(value = "pointCutNoRepeatSubmit(repeatSubmit)", argNames = "joinPoint,repeatSubmit")
    public Object around(ProceedingJoinPoint joinPoint, RepeatSubmit repeatSubmit) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String cmdToken = request.getHeader(LockUtil.HEADER_NAME_CMD_TOKEN);
        if (!HlpUtils.isEmpty(cmdToken) && !LockUtil.cmdTokenValid(cmdToken)) {
            return HttpResult.fail(ErrorCode.CODE_DUP_SUBMIT, ErrorCode.MSG_DUP_SUBMIT);
        }
        try {
            String lockParamsKey = LockUtil.getLockParamsKey(request, repeatSubmit);
            long time = LockUtil.getDupRemainderTime(lockParamsKey);
            if (time > 0) {
                String msg = (repeatSubmit.lockTime() / 1000) + "秒内不能重复提交相同的内容，剩余时间：" + time + " 秒";
                return HttpResult.fail(ErrorCode.CODE_DUP_SUBMIT, msg);
            }
            Lock lock = LockUtil.getLock(lockParamsKey);
            if (lock.tryLock()) {
                LockUtil.putKeyExpired(lockParamsKey, repeatSubmit.lockTime());
                Object retData;
                try {
                    retData = joinPoint.proceed();
                } finally {
                    lock.unlock();
                    if (!HlpUtils.isEmpty(cmdToken)) {
                        LockUtil.removeCmdToken(cmdToken);
                    }
                }
                return retData;
            }
            return HttpResult.fail(ErrorCode.CODE_PROC_ERROR, ErrorCode.MSG_SUBMIT_TOO_FREQUENTLY);
        } catch (Exception e) {
            return HttpResult.fail(ErrorCode.CODE_PROC_ERROR, e.getMessage());
        }
    }
}
